<template>
  <el-dialog v-model="uploadDialogVisible" title="上传图片识别" width="98%" :before-close="closeUploadDialog">
    <div class="upload-container">
      <!-- 内容区域 -->
      <div class="content-wrapper">
        <div class="heads">
          <el-button type="primary" v-if="!companySelect" text @click="addCompany()">添加企业信息</el-button>
        </div>
        <div class="company-form">
          <el-form :inline="true" size="large">
            <el-form-item label="企业:" label-width="80px">
              <el-autocomplete
                :disabled="companySelect"
                v-model="state"
                :fetch-suggestions="querySearchAsync"
                value-key="company_name"
                placeholder="请输入"
                @select="handleSelect"
              />
            </el-form-item>
            <el-form-item label="业务员" label-width="80px">
              <el-select v-model="uid" placeholder="请选择" :disabled="companySelect">
                <el-option v-for="item in listData" :key="item.id" :label="item.nickname" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <div class="result-section">
          <div v-if="tableData.length > 0" class="recognition-result">
            <vxe-table
              border
              show-overflow
              :data="tableData"
              show-footer
              :column-config="{ resizable: true }"
              :edit-config="{ trigger: 'click', mode: 'cell' }"
              :footer-method="footerMethod"
              ref="xTable"
            >
              <vxe-column type="seq" width="60" />
              <vxe-column
                field="acceptorName"
                title="承兑人"
                :edit-render="{ name: 'input', attrs: { type: 'number', placeholder: '请输入' } }"
              >
                <template #edit="{ row }">
                  <vxe-input v-model="row.acceptorName" placeholder="请输入" />
                </template>
              </vxe-column>
              <vxe-column
                field="bill_back_user"
                title="背书人"
                :edit-render="{ name: 'input', attrs: { placeholder: '请输入' } }"
              >
                <template #edit="{ row }">
                  <vxe-input v-model="row.bill_back_user" placeholder="请输入" />
                </template>
              </vxe-column>
              <vxe-column
                field="billAmount"
                title="票面金额"
                width="180"
                :edit-render="{ name: 'input', attrs: { type: 'number', placeholder: '请输入' } }"
              >
                <template #edit="{ row }">
                  <vxe-input v-model="row.billAmount" type="number" placeholder="请输入" />
                </template>
              </vxe-column>
              <vxe-column
                field="expirationDate"
                title="到期日"
                width="180"
                :edit-render="{ name: 'input', attrs: { placeholder: '请输入' } }"
              >
                <template #edit="{ row }">
                  <vxe-input v-model="row.expirationDate" placeholder="请输入" />
                </template>
              </vxe-column>
              <vxe-column
                field="billNo"
                title="票号"
                width="300"
                :edit-render="{ name: 'input', attrs: { placeholder: '请输入' } }"
              >
                <template #edit="{ row }">
                  <vxe-input v-model="row.billNo" placeholder="请输入" />
                </template>
              </vxe-column>
              <vxe-column title="操作" width="100">
                <template #default="{ rowIndex }">
                  <el-button type="danger" size="small" @click="handleDeleteRow(rowIndex)">删除</el-button>
                </template>
              </vxe-column>
            </vxe-table>
          </div>
          <div v-else class="no-result">
            <BillImageUploader @upload-success="handleBillUploadSuccess" @upload-error="handleBillUploadError" />
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeUploadDialog">取消</el-button>
        <el-button type="primary" @click="confirmUpload" :disabled="tableData.length === 0">确定</el-button>
      </div>
    </template>
  </el-dialog>
  <price ref="priceRef" />
</template>

<script lang="ts" setup>
import { ref } from "vue"
import { ElMessage } from "element-plus"
// import { getToken } from "@/utils/cache/cookies" // 未使用的导入
// import { UploadFilled } from "@element-plus/icons-vue" // 未使用的导入
// import { generatePrice, generateDiscount, sumValuesForName } from "@/utils/common" // 未使用的函数
import { sumValuesForName } from "@/utils/common" // 仅使用了sumValuesForName
import { VxeTablePropTypes } from "vxe-table"
// import Decimal from "decimal.js" // 未使用的导入
import { companyListApi } from "@/api/conventional"
import { getAdminRoleListApi } from "@/api/system"
import { doBatchCreateWithCompanyApi } from "@/api/billv2" // 移除未使用的getPendingBillsByCompanyApi
import BillImageUploader from "./BillImageUploader.vue"
import price from "./price.vue"

// 上传API地址 - 已由子组件处理，此处不再需要
// const apiUrl = import.meta.env.VITE_BASE_API + "/Ocr/recognizeGeneral"
// const UploadHeaders = {
//   "X-Token": getToken()
// }

// Emits 定义返回事件
const emit = defineEmits(["recognition-complete", "upload-close"])

// 控制上传弹框
const uploadDialogVisible = ref(false)

// 按钮类型：pending(待入库)或incomplete(入库未完成)
// const buttonType = ref<string>("pending")

// 当前调用方的标识符
const currentContextKey = ref<string>("")

// 上传文件列表 - 已由子组件处理
// const fileList = ref<any[]>([])

// 当前预览图片的 URL - 已由子组件处理
// const previewUrl = ref("")

// 识别结果
const recognitionResult = ref<Record<string, string> | null>(null)

// 表格数据
const tableData = ref<any[]>([])
const xTable = ref<any>(null)

// 企业和业务员相关
const listData = ref<any>([])
const state = ref("")
const uid = ref<number>(0)
const company_id = ref<number>(0)
const companySelect = ref<boolean>(false)

// 是/否选项列表 - 未在当前组件中使用
// const sexList1 = ref([
//   { label: "是", value: 1 },
//   { label: "否", value: 2 }
// ])

// 格式化是/否显示 - 未在当前组件中使用
// const formatSex = (value: number) => {
//   if (value === 1) {
//     return "是"
//   }
//   if (value === 2) {
//     return "否"
//   }
//   return ""
// }

// 表格底部统计方法
const footerMethod: VxeTablePropTypes.FooterMethod<any> = ({ columns, data }) => {
  return [
    columns.map((column, columnIndex) => {
      if (columnIndex === 0) {
        return "统计"
      }
      if (["billAmount", "enter_discount", "enter_finally"].includes(column.field)) {
        return sumValuesForName(data, column.field)
      }

      return null
    })
  ]
}

// 日期选择相关 - 未在当前组件中使用
// const value2 = ref("")
// const customDateTimeFormat = ref<string>("YYYY-MM-DD HH:mm:ss")
// const shortcuts = [
//   {
//     text: "今天",
//     value: new Date()
//   },
//   {
//     text: "昨天",
//     value: () => {
//       const date = new Date()
//       date.setDate(date.getDate() - 1)
//       return date
//     }
//   },
//   {
//     text: "一周前",
//     value: () => {
//       const date = new Date()
//       date.setDate(date.getDate() - 7)
//       return date
//     }
//   }
// ]

// 上传数据对象，包含固定的type参数
const UploadData = {
  type: "discount",
  company_name: "",
  company_id: company_id.value
}
// 加载待处理票据数据 - 未在当前组件中调用
// const loadPendingBillsData = async (companyId: number, contextKey: string) => {
//   const { code, data } = await getPendingBillsByCompanyApi({
//     company_id: companyId,
//     company_name: contextKey,
//     buttonType: buttonType.value
//   })

//   if (code === 200 && data.list && data.list.length > 0) {
//     // 将API返回的数据转换为表格所需格式
//     tableData.value = data.list.map((item: any) => ({
//       bill_id: item.bill_id || "",
//       acceptorName: item.acceptorName || "",
//       billAmount: item.billAmount || "",
//       expirationDate: item.expirationDate || "",
//       billNo: item.billNo || "",
//       enter_price: item.enter_price || "",
//       enter_discount: item.enter_discount || "",
//       enter_finally: item.enter_finally || "",
//       enter_time: item.enter_time || "",
//       enter_invoicings: item.enter_invoicings || 2, // 默认否
//       enter_checks: item.enter_checks || 2, // 默认否
//       remark: item.remark || ""
//     }))
//     // 根据buttonType显示不同的提示信息
//     if (buttonType.value === "pending") {
//       ElMessage.success("已加载企业待入库票据数据")
//     } else if (buttonType.value === "incomplete") {
//       ElMessage.success("已加载企业入库未完成票据数据")
//     } else {
//       ElMessage.success("已加载企业待处理票据数据")
//     }
//   } else {
//     ElMessage.info("暂无票据数据")
//     tableData.value = []
//   }
// }

// 添加企业信息
const priceRef = ref<any>()
const addCompany = () => {
  if (priceRef.value) {
    priceRef.value.show()
  }
}

// 打开上传弹框，并传入调用方标识符
const openUploadDialog = () => {
  uploadDialogVisible.value = true

  // 加载业务员列表
  getAdminList()
}
defineExpose({ openUploadDialog })

// 关闭上传弹框
const closeUploadDialog = () => {
  uploadDialogVisible.value = false
  resetUploadDialog() // 重置弹框数据
  // 触发取消事件，传递当前 contextKey
  emit("upload-close", currentContextKey.value)
}

// 重置上传弹框的状态
const resetUploadDialog = () => {
  // fileList.value = [] // 清空文件列表 - 已由子组件处理
  currentContextKey.value = "" // 清空调用方标识符
  // previewUrl.value = "" // 清空预览 URL - 已由子组件处理
  recognitionResult.value = null // 清空识别结果
  tableData.value = [] // 清空表格数据
  state.value = "" // 清空企业
  uid.value = 0 // 清空业务员
  company_id.value = 0 // 清空企业ID
  UploadData.company_id = 0
  UploadData.company_name = ""
}

// 获取业务员列表
const getAdminList = async () => {
  await getAdminRoleListApi({
    role_ids: 2
  })
    .then((res) => {
      listData.value = res.data
    })
    .catch(() => {})
    .finally(() => {})
}

// 企业搜索
const querySearchAsync = (queryString: string, cb: (arg: any) => void) => {
  state.value = queryString
  companyListApi({
    company_name: state.value
  }).then((res) => {
    const lists = res.data
    if (lists.length == 0) {
      ElMessage.error("请先添加企业信息")
      cb([])
    } else {
      cb(lists)
    }
  })
}

// 企业选择处理
const handleSelect = (item: any) => {
  uid.value = item.uid
  company_id.value = item.id
}

// 确认上传操作
const confirmUpload = async () => {
  // 检查是否有表格数据
  if (tableData.value.length === 0) {
    ElMessage.warning("暂无识别结果，请先上传图片")
    return
  }

  // 检查是否选择了企业和业务员
  if (company_id.value === 0) {
    ElMessage.warning("请选择企业")
    return
  }

  if (uid.value === 0) {
    ElMessage.warning("请选择业务员")
    return
  }

  try {
    console.log(tableData.value)

    await doBatchCreateWithCompanyApi({
      enter_company_id: company_id.value,
      enter_admin_id: uid.value,
      batch_list: tableData.value
    })

    ElMessage.success("操作成功")

    emit("upload-close", currentContextKey.value)
    resetUploadDialog() // 重置弹框数据
    uploadDialogVisible.value = false
  } catch (error) {
    ElMessage.error("操作失败，请重试")
  }
}

// 以下函数已由子组件BillImageUploader处理，不再需要
// // 删除图片
// const handleRemove = () => {
//   ElMessage.success("图片已删除")
//   previewUrl.value = "" // 清空预览 URL
//   recognitionResult.value = null // 清空识别结果
// }

// // 原有上传成功处理函数
// const handleSuccess = (response: any) => {
//   // ElMessage.success("图片上传成功")
//   const data = response.data
//   console.log("handleSuccess")
//   console.log(data, "handleSuccess")
//   const code = response.code
//   // 检查返回的数据格式
//   if (code === 200 && data && data.data && data.data.length > 0) {
//     // 根据返回的结果去对应写入表格
//     data.data.forEach((item: any) => {
//       const existingRow = tableData.value.find((row) => row.billAmount == item.billAmount)
//       if (existingRow) {
//         // 如果票据号已存在，则更新相关字段
//         existingRow.enter_price = item.enter_price || ""
//         existingRow.enter_discount = item.enter_discount || ""
//         existingRow.enter_finally = item.enter_finally || ""
//         existingRow.enter_time = item.enter_time || ""
//       }
//     })
//     nextTick(() => {
//       xTable.value.refreshColumn()
//     })
//     // // 直接使用返回的数据填充表格
//     // tableData.value = response.data.data.map((item: any) => ({
//     //   bill_id: item.bill_id,
//     //   acceptorName: item.acceptorName,
//     //   billAmount: item.billAmount,
//     //   expirationDate: item.expirationDate,
//     //   billNo: item.billNo,
//     //   enter_price: item.enter_price || "",
//     //   enter_discount: item.enter_discount || "",
//     //   enter_finally: item.enter_finally || "",
//     //   enter_time: item.enter_time || "",
//     //   enter_invoicings: item.enter_invoicings || 2, // 默认否
//     //   enter_checks: item.enter_checks || 2, // 默认否
//     //   remark: ""
//     // }))
//     // ElMessage.success("图片识别完成")
//   } else {
//     // 如果没有识别结果数据，则使用原来的模拟方式
//     ElMessage.error("图片识别失败，请重新上传")
//   }
// }

// 新的子组件上传成功处理函数
const handleBillUploadSuccess = (data: any[]) => {
  // 将识别结果转换为表格数据格式
  const newTableData = data.map((item: any) => ({
    acceptorName: item.acceptorName || "",
    billAmount: item.billAmount || "",
    expirationDate: item.expirationDate || "",
    bill_back_user: item.bill_back_user || "",
    billNo: item.billNo || ""
  }))

  // 更新表格数据
  tableData.value = newTableData

  ElMessage.success("票据识别成功，已加载数据")
}

// 新的子组件上传失败处理函数
const handleBillUploadError = (error: any) => {
  console.error("票据上传失败:", error)
  ElMessage.error("票据上传失败，请重试")
}

// 以下函数在当前组件中未被调用
// // 处理价格输入
// const handleInput = (row: any) => {
//   const { finallyAmount, discountAmount } = generatePrice(
//     row.enter_price,
//     row.enter_finally,
//     row.enter_discount,
//     row.billAmount,
//     false
//   )
//   row.enter_finally = finallyAmount
//   row.enter_discount = discountAmount
// }

// // 处理贴息费输入
// const handleDiscount = (row: any) => {
//   const { price, finallyAmount } = generateDiscount(
//     row.enter_price,
//     row.enter_finally,
//     row.enter_discount,
//     row.billAmount,
//     false
//   )
//   row.enter_price = price
//   row.enter_finally = finallyAmount
// }

// // 处理实付金额输入
// const handleFinally = (row: any) => {
//   const billAmount = new Decimal(row.billAmount).times(10000)
//   const enter_finally = new Decimal(row.enter_finally)
//   const discountAmount = billAmount.minus(enter_finally).toNumber()
//   const { price } = generateDiscount(row.enter_price, row.enter_finally, discountAmount, billAmount.toString(), true)
//   row.enter_price = price.toFixed(2)
//   row.enter_discount = discountAmount
// }

// // 批量设置开票状态
// const setAllEnterInvoicings = (value: number) => {
//   tableData.value.forEach((row: any) => {
//     row.enter_invoicings = value
//   })
// }

// // 批量设置先款先票状态
// const setAllEnterChecks = (value: number) => {
//   tableData.value.forEach((row: any) => {
//     row.enter_checks = value
//   })
// }

// // 批量设置日期
// const handleDateChange = (value: any) => {
//   tableData.value.forEach((row: any) => {
//     row.enter_time = value
//   })
// }

// 删除行
const handleDeleteRow = (rowIndex: number) => {
  if (rowIndex >= 0 && rowIndex < tableData.value.length) {
    tableData.value.splice(rowIndex, 1)
    ElMessage.success("行数据已删除")
  }
}

// 以下函数已由子组件BillImageUploader处理，不再需要
// // 上传失败
// const handleError = (error: any, file: any, fileList: any[]) => {
//   ElMessage.error("图片上传失败")
//   // 从 fileList 中移除失败的文件
//   const index = fileList.findIndex((item) => item.uid === file.uid)
//   if (index !== -1) {
//     fileList.splice(index, 1)
//   }
// }

// // 上传前校验图片
// const beforeUpload = (file: File) => {
//   const isImage = file.type.startsWith("image/")
//   const isLt5M = file.size / 1024 / 1024 < 5

//   if (!isImage) {
//     ElMessage.error("上传文件必须是图片格式!")
//     return false
//   }
//   if (!isLt5M) {
//     ElMessage.error("上传图片大小不能超过 5MB!")
//     return false
//   }
//   return true
// }

// // 超出限制处理
// const handleExceed = () => {
//   ElMessage.warning("最多只能上传 1 张图片")
// }
</script>

<style scoped lang="scss">
.upload-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.content-wrapper {
  display: flex;
  flex-direction: column;
  gap: 20px;
  min-height: 300px;
  padding: 20px 0;
}

.heads {
  display: flex;
  justify-content: end;
  margin-bottom: 10px;
}

.company-form {
  margin-bottom: 20px;
}

.upload-section {
  margin-bottom: 20px;
}

.recognition-result {
  width: 100%;
}

.recognition-header {
  margin-bottom: 20px;
}

.no-result {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.heads2 {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

.bolck {
  margin-left: 10px;
}
</style>
